import SwiftUI
import Foundation

/*
 * 图表示例
 */
class MainFrame: FCUIView{
    var m_chart = FCChart()
    
    var latestDataStr = ""
    var findMyCharts = [FCView]()
    var charts = [FCChart]()
    var gridStocks : FCGrid = FCGrid()
    let strCode = "600000.SH"
    let strName = "浦发银行"
    let isMobile = false
    
    func drawLatestDiv(view:FCView, paint:FCPaint, clipRect:FCRect) {
        let avgHeight = 20.0
        var drawFont = "Default,14"
        if self.isMobile {
            drawFont = "Default,12"
        }
        var dTop = 30.0
        paint.drawLine(color:view.borderColor, width:1, style:[], x1:0, y1:dTop, x2:view.size.cx, y2:dTop)
        let dataStrs = latestDataStr.split(separator: ",")
        var lastClose = 0.0
        var priceList = [Double]()
        var volList = [Double]()
        var buySellTexts = [String]()
        if dataStrs.count > 10 {
            paint.drawText(text:String(dataStrs[0]), color:"rgb(175,196,228)", font:"Default,14", x:5, y:7)
            paint.drawText(text:String(dataStrs[1]), color:"rgb(194,151,18)", font:"Default,14", x:80, y:7)
            lastClose = StringToFloat(str:String(dataStrs[8]))
            priceList.append(StringToFloat(str:String(dataStrs[23])))
            priceList.append(StringToFloat(str:String(dataStrs[22])))
            priceList.append(StringToFloat(str:String(dataStrs[21])))
            priceList.append(StringToFloat(str:String(dataStrs[20])))
            priceList.append(StringToFloat(str:String(dataStrs[19])))
            priceList.append(StringToFloat(str:String(dataStrs[9])))
            priceList.append(StringToFloat(str:String(dataStrs[10])))
            priceList.append(StringToFloat(str:String(dataStrs[11])))
            priceList.append(StringToFloat(str:String(dataStrs[12])))
            priceList.append(StringToFloat(str:String(dataStrs[13])))
            
            volList.append(StringToFloat(str:String(dataStrs[28])))
            volList.append(StringToFloat(str:String(dataStrs[27])))
            volList.append(StringToFloat(str:String(dataStrs[26])))
            volList.append(StringToFloat(str:String(dataStrs[25])))
            volList.append(StringToFloat(str:String(dataStrs[24])))
            volList.append(StringToFloat(str:String(dataStrs[14])))
            volList.append(StringToFloat(str:String(dataStrs[15])))
            volList.append(StringToFloat(str:String(dataStrs[16])))
            volList.append(StringToFloat(str:String(dataStrs[17])))
            volList.append(StringToFloat(str:String(dataStrs[18])))
        }
        buySellTexts.append("卖5")
        buySellTexts.append("卖4")
        buySellTexts.append("卖3")
        buySellTexts.append("卖2")
        buySellTexts.append("卖1")
        buySellTexts.append("买1")
        buySellTexts.append("买2")
        buySellTexts.append("买3")
        buySellTexts.append("买4")
        buySellTexts.append("买5")
        var textColor = "rgb(175,196,228)"
        if view.getPaint().defaultUIStyle == "light" {
            textColor = "rgb(0,0,0)"
        }
        let maxVol = maxValue(list:volList)
        for i in 0...9 {
            let tSize = paint.textSize(text:buySellTexts[i], font:drawFont)
            paint.drawText(text:buySellTexts[i], color:textColor, font:drawFont, x:5, y:dTop + avgHeight / 2 - tSize.cy / 2)
            if priceList.count > 0 {
                let price = priceList[i]
                var upDownColor = "rgb(255,82,82)"
                var upDownColor2 = "rgba(255,82,82,50)"
                if price < lastClose {
                    upDownColor = "rgb(46,255,50)"
                    upDownColor2 = "rgba(46,255,50,50)"
                } 
                if self.isMobile {
                    paint.drawText(text:toFixed(value:priceList[i], digit:2), color:upDownColor, font:drawFont, x:40, y:dTop + avgHeight / 2 - tSize.cy / 2)
                } else {
                    paint.drawText(text:toFixed(value:priceList[i], digit:2), color:upDownColor, font:drawFont, x:50, y:dTop + avgHeight / 2 - tSize.cy / 2)
                }
                if (maxVol > 0) {
                    if self.isMobile {
                        paint.fillRect(color:upDownColor2, left:view.size.cx - volList[i] * 50 / maxVol, top:dTop + 2, right:view.size.cx, bottom:dTop + avgHeight - 2)
                    } else {
                        paint.fillRect(color:upDownColor2, left:view.size.cx - volList[i] * 80 / maxVol, top:dTop + 2, right:view.size.cx, bottom:dTop + avgHeight - 2)
                    }
                }
                let volText = toFixed(value:volList[i] / 100, digit:0)
                let volTextSize = paint.textSize(text:volText, font:drawFont)
                paint.drawText(text:volText, color:textColor, font:drawFont, x:view.size.cx - volTextSize.cx - 10, y:dTop + avgHeight / 2 - volTextSize.cy / 2)
            }
            dTop += avgHeight
        }
        paint.drawLine(color:view.borderColor, width:1, style:[], x1:0, y1:dTop, x2:view.size.cx, y2:dTop)
        paint.drawText(text:"现价", color:"rgb(175,196,228)", font:drawFont, x:5, y:dTop + 10)
        paint.drawText(text:"幅度", color:"rgb(175,196,228)", font:drawFont, x:5, y:dTop + 35)
        paint.drawText(text:"总额", color:"rgb(175,196,228)", font:drawFont, x:5, y:dTop + 60)
        paint.drawText(text:"总量", color:"rgb(175,196,228)", font:drawFont, x:5, y:dTop + 85)
        paint.drawText(text:"开盘", color:"rgb(175,196,228)", font:drawFont, x:110, y:dTop + 10)
        paint.drawText(text:"振幅", color:"rgb(175,196,228)", font:drawFont, x:110, y:dTop + 35)
        paint.drawText(text:"最高", color:"rgb(175,196,228)", font:drawFont, x:110, y:dTop + 60)
        paint.drawText(text:"最低", color:"rgb(175,196,228)", font:drawFont, x:110, y:dTop + 85)
        if dataStrs.count > 10 {
            let close = StringToFloat(str:String(dataStrs[2]))
            let high = StringToFloat(str:String(dataStrs[3]))
            let low = StringToFloat(str:String(dataStrs[4]))
            let open = StringToFloat(str:String(dataStrs[5]))
            let volume = StringToFloat(str:String(dataStrs[6]))
            let amount = StringToFloat(str:String(dataStrs[7]))
            var diff = 0.0
            if lastClose > 0{
                diff = 100 * (close - lastClose) / lastClose
            }
            
            var diff2 = 0.0
            if lastClose > 0{
                diff2 = 100 * (high - lastClose) / lastClose - 100 * (low - lastClose) / lastClose
            }
            paint.drawText(text:toFixed(value:close, digit:2), color:getPriceColor(price:close, comparePrice:lastClose), font:drawFont, x:40, y:dTop + 10)
            paint.drawText(text:toFixed(value:diff, digit:2) + "%", color:getPriceColor(price:close, comparePrice:lastClose), font:drawFont, x:40, y:dTop + 35)
            paint.drawText(text:toFixed(value:amount / 10000, digit:0), color:textColor, font:drawFont, x:40, y:dTop + 60)
            paint.drawText(text:toFixed(value:volume / 10000, digit:0), color:textColor, font:drawFont, x:40, y:dTop + 85)
            
            paint.drawText(text:toFixed(value:open, digit:2), color:getPriceColor(price:open, comparePrice:lastClose), font:drawFont, x:150, y:dTop + 10)
            paint.drawText(text:toFixed(value:diff2, digit:2) + "%", color:getPriceColor(price:close, comparePrice:lastClose), font:drawFont, x:150, y:dTop + 35)
            paint.drawText(text:toFixed(value:high, digit:2), color:getPriceColor(price:high, comparePrice:lastClose), font:drawFont, x:150, y:dTop + 60)
            paint.drawText(text:toFixed(value:low, digit:2), color:getPriceColor(price:low, comparePrice:lastClose), font:drawFont, x:150, y:dTop + 85)
        }
    }
    
    func getPriceColor(price : Double, comparePrice : Double) -> String{
        if price != 0
        {
            if price > comparePrice
            {
                return "rgb(255,82,82)"
            }
            else if price < comparePrice
            {
                return "rgb(46,255,50)"
            }
        }
        return "rgb(190,190,235)"
    }
    
    /*
     * 创建列
     * grid:表格
     */
    func createGridCell(grid : FCGrid) ->FCGridCell {
        let gridCell = FCGridCell()
        if grid.getPaint().defaultUIStyle == "dark" {
            gridCell.backColor = "none"
            gridCell.borderColor = "none"
            gridCell.textColor = "rgb(175,196,228)"
        } else if grid.getPaint().defaultUIStyle == "light" {
            gridCell.backColor = "none"
            gridCell.borderColor = "none"
            gridCell.textColor = "rgb(0,0,0)"
        }
        gridCell.font = "Default,13"
        return gridCell
    }
    
    /*
     * 根据名称查找视图
     * name:名称
     * views:视图集合
     */
    func findViewsByType(findType : String, views : [FCView], refViews : inout [FCView]) {
        let size = views.count
        for i in 0...size - 1{
            let view = views[i]
            if view.viewType == findType {
                refViews.append(view)
            } else {
                if view.views.count > 0 {
                    findViewsByType(findType : findType, views : view.views, refViews : &refViews)
                }
            }
        }
    }
    
    /*
     * 黑色风格
     */
    func toBlackChart(chart : FCChart, index:Int32) {
        chart.getPaint().defaultUIStyle = "dark"
        chart.backColor = "rgb(0,0,0)"
        chart.borderColor = "none"
        chart.textColor = "rgb(175,196,228)"
        chart.scaleColor = "rgb(75,75,75)"
        chart.crossTipColor = "rgb(50,50,50)"
        chart.crossLineColor = "rgb(100,100,100)"
        chart.gridColor = "rgb(50,50,50)"
        if(index > 0){
            chart.upColor = "rgb(186,56,18)"
            chart.downColor = "rgb(31,182,177)"
        }else{
            chart.upColor = "rgb(255,82,82)"
            chart.downColor = "rgb(46,255,50)"
        }
        chart.barStyle = "rect2"
        chart.candleStyle = "rect2"
        chart.trendColor = "rgb(255,255,255)"
        chart.hScaleTextColor = "rgb(194,151,18)"
        chart.vScaleTextColor = "rgb(194,151,18)"
    }
    
    /*
     * 请求报价数据
     */
    func queryPrice(codes : String){
        let strUrl = "http://110.42.188.197:9968/quote?func=price&count=500&codes=" + codes
        if let url = URL(string: strUrl) {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                if let error = error {
                    print("Error: \(error)")
                    return
                }
                if let result = String(data: data!, encoding: .utf8) {
                    DispatchQueue.main.async {
                        let strs = result.split(separator:"\r\n")
                        for i in 0...strs.count - 1{
                            let subStrs = strs[i].split(separator:",")
                            if subStrs.count >= 15{
                                let row = FCGridRow()
                                self.gridStocks.rows.append(row)
                                let cell1 = self.createGridCell(grid:self.gridStocks)
                                cell1.value = String(i)
                                row.cells.append(cell1)
                                
                                let cell2 = self.createGridCell(grid:self.gridStocks)
                                cell2.value = String(subStrs[0])
                                cell2.textColor = "rgb(194,151,18)"
                                row.cells.append(cell2)
                                
                                let cell3 = self.createGridCell(grid:self.gridStocks)
                                cell3.value = String(subStrs[1])
                                row.cells.append(cell3)
                                
                                let close = StringToFloat(str:String(subStrs[2]))
                                let high = StringToFloat(str:String(subStrs[3]))
                                let low =  StringToFloat(str:String(subStrs[4]))
                                let lastClose = StringToFloat(str:String(subStrs[8]))
                                let cell4 = self.createGridCell(grid:self.gridStocks)
                                cell4.value = toFixed(value:close, digit:2)
                                cell4.textColor = self.getPriceColor(price:close, comparePrice:lastClose)
                                row.cells.append(cell4)
                                
                                var diff = 0.0
                                if lastClose > 0{
                                    diff = 100.0 * (close - lastClose) / lastClose
                                }
                                let cell5 = self.createGridCell(grid:self.gridStocks)
                                cell5.value = toFixed(value:diff, digit:2) + "%"
                                cell5.textColor = self.getPriceColor(price:diff, comparePrice:0)
                                row.cells.append(cell5)
                                
                                let cell6 = self.createGridCell(grid:self.gridStocks)
                                cell6.value = toFixed(value:close - lastClose, digit:2)
                                cell6.textColor = self.getPriceColor(price:close, comparePrice:lastClose)
                                row.cells.append(cell6)
                                
                                let volume = StringToFloat(str:String(subStrs[6]))
                                let amount = StringToFloat(str:String(subStrs[7]))
                                let cell7 = self.createGridCell(grid:self.gridStocks)
                                cell7.value = toFixed(value:volume / (100 * 10000), digit:2) + "万"
                                row.cells.append(cell7)
                                
                                let cell8 = self.createGridCell(grid:self.gridStocks)
                                cell8.value = toFixed(value:amount / 100000000, digit:2) + "亿"
                                row.cells.append(cell8)
                                
                                let cell9 = self.createGridCell(grid:self.gridStocks)
                                cell9.value = toFixed(value:Double(String(subStrs[12]))!, digit:2)
                                row.cells.append(cell9)
                                
                                let cell10 = self.createGridCell(grid:self.gridStocks)
                                cell10.value = toFixed(value:Double(String(subStrs[11]))!, digit:2)
                                row.cells.append(cell10)
                                
                                var diff2 = 0.0
                                if(lastClose > 0){
                                    diff2 = 100.0 * (high - lastClose) / lastClose - 100.0 * (low - lastClose) / lastClose
                                }
                                let cell11 = self.createGridCell(grid:self.gridStocks)
                                cell11.value = toFixed(value:diff2, digit:2) + "%"
                                row.cells.append(cell11)
                                
                                let cell12 = self.createGridCell(grid:self.gridStocks)
                                cell12.value = toFixed(value:Double(String(subStrs[13]))!, digit:2)
                                row.cells.append(cell12)
                                
                                let marketValue = Double(String(subStrs[9]))! * close
                                let cell13 = self.createGridCell(grid:self.gridStocks)
                                cell13.value = toFixed(value:marketValue / 100000000, digit:2) + "亿"
                                row.cells.append(cell13)
                                
                                let flowValue = Double(String(subStrs[10]))! * close
                                let cell14 = self.createGridCell(grid:self.gridStocks)
                                cell14.value = toFixed(value:flowValue / 100000000, digit:2) + "亿"
                                row.cells.append(cell14)
                                
                                let cell15 = self.createGridCell(grid:self.gridStocks)
                                cell15.value = ""
                                row.cells.append(cell15)
                                
                                let upperLimit = Double(String(subStrs[14]))!
                                let lowerLimit = Double(String(subStrs[15]))!
                                let cell16 = self.createGridCell(grid:self.gridStocks)
                                cell16.value = toFixed(value:upperLimit, digit:2)
                                cell16.textColor = self.getPriceColor(price:1, comparePrice: 0)
                                row.cells.append(cell16)
                                
                                let cell17 = self.createGridCell(grid:self.gridStocks)
                                cell17.value = toFixed(value:lowerLimit, digit:2)
                                cell17.textColor = self.getPriceColor(price:0, comparePrice:1)
                                row.cells.append(cell17)
                                
                                let cell18 = self.createGridCell(grid:self.gridStocks)
                                cell18.value = ""
                                row.cells.append(cell18)
                                
                                let cell19 = self.createGridCell(grid:self.gridStocks)
                                cell19.value = ""
                                row.cells.append(cell19)
                                
                                let cell20 = self.createGridCell(grid:self.gridStocks)
                                cell20.value = ""
                                row.cells.append(cell20)
                                
                                let cell21 = self.createGridCell(grid:self.gridStocks)
                                cell21.value = ""
                                row.cells.append(cell21)
                                
                                let cell22 = self.createGridCell(grid:self.gridStocks)
                                cell22.value = ""
                                row.cells.append(cell22)
                            }
                        }
                        invalidateView(view:self.gridStocks)
                    }
                }
            }
            task.resume()
        }
    }
    
    /*
     * 请求最新数据
     */
    func queryNewData(code : String){
        let strUrl = "http://110.42.188.197:9968/quote?func=getnewdata&codes=" + code
        if let url = URL(string: strUrl) {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                if let error = error {
                    print("Error: \(error)")
                    return
                }
                if let result = String(data: data!, encoding: .utf8) {
                    DispatchQueue.main.async {
                        self.latestDataStr = result
                        invalidate(paint:self.gPaint)
                    }
                }
            }
            task.resume()
        }
    }
    
    /*
     * 请求历史数据
     */
    func queryHistoryData(mychart : FCView, chart : FCChart, code : String) {
        if let strCycle = mychart.exAttributes["cycle"]{
            let intCycle = Int(strCycle)!
            var strUrl = "http://110.42.188.197:9968/quote?func=getkline&code=" + code +  "&cycle=" + strCycle + "&count=500"
            if intCycle == 0{
                strUrl = "http://110.42.188.197:9968/quote?func=getkline&code=" + code +  "&cycle=0&count=240"
            }
            if let url = URL(string: strUrl) {
                let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                    if let error = error {
                        print("Error: \(error)")
                        return
                    }
                    if let result = String(data: data!, encoding: .utf8) {
                        DispatchQueue.main.async {
                            let strs = result.split(separator:"\r\n")
                            var dataList = [SecurityData]()
                            chart.firstOpen = 0
                            if intCycle == 0{
                                let fStrs = strs[0].split(separator:" ")
                                if fStrs.count >= 3{
                                    chart.firstOpen = StringToFloat(str:String(fStrs[2]))
                                }
                            }
                            for i in 2...strs.count - 1{
                                let subStrs = strs[i].split(separator:",")
                                if subStrs.count >= 7{
                                    let data = SecurityData()
                                    if intCycle < 1440{
                                        let dateStr = String(subStrs[0])
                                        var timeStr = String(subStrs[1])
                                        timeStr = timeStr.prefix(2) + ":" + timeStr.suffix(2) + ":00"
                                        data.open = StringToFloat(str:String(subStrs[2]))
                                        data.high = StringToFloat(str:String(subStrs[3]))
                                        data.low = StringToFloat(str:String(subStrs[4]))
                                        data.close = StringToFloat(str:String(subStrs[5]))
                                        data.volume = StringToFloat(str:String(subStrs[6]))
                                        let dateFormatter = DateFormatter()
                                        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                                        let nDate = dateFormatter.date(from: dateStr + " " + timeStr)
                                        data.date = nDate!.timeIntervalSince1970
                                        if intCycle == 0 && (data.volume > 0 || dataList.count == 0){
                                            chart.lastValidIndex = dataList.count
                                            if(chart.firstOpen == 0){
                                                chart.firstOpen = data.close
                                            }
                                        }
                                    }else{
                                        let dateStr = String(subStrs[0])
                                        data.open = StringToFloat(str:String(subStrs[1]))
                                        data.high = StringToFloat(str:String(subStrs[2]))
                                        data.low = StringToFloat(str:String(subStrs[3]))
                                        data.close = StringToFloat(str:String(subStrs[4]))
                                        data.volume = StringToFloat(str:String(subStrs[5]))
                                        let dateFormatter = DateFormatter()
                                        dateFormatter.dateFormat = "yyyy-MM-dd"
                                        let nDate = dateFormatter.date(from: dateStr)
                                        data.date = nDate!.timeIntervalSince1970
                                    }
                                    dataList.append(data)
                                }
                            }
                            if intCycle == 0{
                                chart.autoFillHScale = true
                                chart.cycle = "trend"
                            }else if intCycle < 1440{
                                chart.cycle = "minute"
                            }else{
                                chart.cycle = "day"
                            }
                            chart.datas = dataList
                            let maxVisibleRecord = getChartMaxVisibleCount(chart:chart, hScalePixel: chart.hScalePixel, pureH: getChartWorkAreaWidth(chart:chart))
                            chart.lastVisibleIndex = chart.datas.count - 1
                            if maxVisibleRecord > chart.datas.count {
                                chart.firstVisibleIndex = 0
                            } else {
                                chart.firstVisibleIndex = chart.lastVisibleIndex - maxVisibleRecord + 1
                            }
                            resetChartVisibleRecord(chart:chart)
                            checkChartLastVisibleIndex(chart:chart)
                            calcChartIndicator(chart:chart)
                            invalidateView(view:chart)
                        }
                    }
                }
                task.resume()
            }
        }
    }
    
    /*
     * 重绘背景的实现方法
     * view:视图
     * paint:绘图对象
     * clipRect:裁剪区域
     */
    func onPaint(view:FCView, paint:FCPaint, clipRect:FCRect) {
        if view.viewType == "latestdiv"{
            drawLatestDiv(view:view, paint:paint, clipRect:clipRect)
        }else{
            onPaintDefault(view: view, paint: paint, clipRect: clipRect)
        }
    }
    
    /*
    * 点击单元格
    * grid:表格
    * row:行
    * column:列
    * cell:单元格
    * firstTouch:是否第一次触摸
    * firstPoint:第一次触摸的坐标
    * secondTouch:是否第二次触摸
    * secondPoint:第二次触摸的坐标
    * clcks:点击次数
    */
    func onClickGridCell(grid:FCGrid, row:FCGridRow, column:FCGridColumn, cell:FCGridCell, firstTouch:Bool, firstPoint:FCPoint, secondTouch:Bool, secondPoint:FCPoint, clicks:Int){
        let code = row.cells[1].value
        let name = row.cells[2].value
        for i in 0...2{
            let myChart = findMyCharts[i]
            let chart = charts[i]
            chart.text = code + " " + name
            queryHistoryData(mychart:myChart, chart:chart, code:code)
        }
        queryNewData(code:code)
        invalidate(paint:grid.getPaint())
    }
    
    /*
    * 点击方法
    * view:视图
    * firstTouch:是否第一次触摸
    * firstPoint:第一次触摸的坐标
    * secondTouch:是否第二次触摸
    * secondPoint:第二次触摸的坐标
    * clicks:点击次数
    */
    func onClick(view:FCView, firstTouch:Bool, firstPoint:FCPoint, secondTouch:Bool, secondPoint:FCPoint, clicks:Int) {
        onClickDefault(view: view, firstTouch: firstTouch, firstPoint: firstPoint, secondTouch: secondTouch, secondPoint: secondPoint, clicks: clicks)
        if(view.viewName.contains("cycle,")){
            let strs = view.viewName.split(separator: ",")
            let index = Int(String(strs[1]))!
            let cycleInt = Int(String(strs[2]))!
            findMyCharts[index].exAttributes["cycle"] = String(cycleInt)
            queryHistoryData(mychart:findMyCharts[index], chart:charts[index], code:String(charts[index].text.split(separator: " ")[0]))
        }
    }
    
    /**
     * 绘制横轴刻度的自定义方法
     * chart:图表
     * paint:绘图对象
     * clipRect:裁剪区域
     */
    func drawChartHScale(chart:FCChart, paint:FCPaint, clipRect:FCRect){
        if chart.datas.count > 0 && chart.hScaleHeight > 0 {
            if chart.lastVisibleIndex - chart.firstVisibleIndex > 0{
                if chart.cycle == "trend"{
                    var times = [Int]()
                    if chart.size.cx < 600
                    {
                        times.append(10 * 60 + 30)
                        times.append(11 * 60 + 30)
                        times.append(14 * 60)
                    }else{
                        times.append(10 * 60)
                        times.append(10 * 60 + 30)
                        times.append(11 * 60)
                        times.append(11 * 60 + 30)
                        times.append(13 * 60 + 30)
                        times.append(14 * 60)
                        times.append(14 * 60 + 30)
                    }
                    for i in chart.firstVisibleIndex...chart.lastVisibleIndex{
                        let dateNum = chart.datas[i].date
                        let timeInterval:TimeInterval = TimeInterval(dateNum)
                        let date = Date(timeIntervalSince1970: timeInterval)
                        let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
                        let hour = Int(components.hour!)
                        let minute = Int(components.minute!)
                        for j in 0...times.count - 1{
                            if times[j] == hour * 60 + minute{
                                let x = getChartX(chart: chart, index: i)
                                let bBottom = chart.size.cy
                                paint.drawLine(color:chart.scaleColor, width:1, style:[], x1:x, y1:bBottom - chart.hScaleHeight, x2:x, y2:bBottom - chart.hScaleHeight + 12)
                                paint.drawLine(color:chart.gridColor, width:1, style:[], x1:x, y1:0, x2:x, y2:bBottom - chart.hScaleHeight)
                                let dateformatter = DateFormatter()
                                dateformatter.dateFormat = "HH:mm"
                                let xText =  dateformatter.string(from:date)
                                let tSize = paint.textSize(text:xText, font:"Default,12")
                                paint.drawText(text:xText, color:chart.hScaleTextColor, font:"Default,12", x:x - tSize.cx / 2, y:bBottom - chart.hScaleHeight / 2 - tSize.cy / 2)
                                break
                            }
                        }
                    }
                }else if chart.cycle == "minute"{
                    var lastYear = 0
                    var lastDate2 = 0.0
                    let dLeft = chart.leftVScaleWidth
                    var i = chart.firstVisibleIndex
                    while i <= chart.lastVisibleIndex{
                        let dateNum = chart.datas[i].date
                        let timeInterval:TimeInterval = TimeInterval(dateNum)
                        let date = Date(timeIntervalSince1970: timeInterval)
                        let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
                        let year = Int(components.year!)
                        var xText = ""
                        if year != lastYear
                        {
                            let dateformatter = DateFormatter()
                            dateformatter.dateFormat = "yyyy/MM/dd"
                            xText =  dateformatter.string(from:date)
                        }
                        else
                        {
                            let dateformatter = DateFormatter()
                            dateformatter.dateFormat = "MM/dd"
                            xText =  dateformatter.string(from:date)
                        }
                        if Int(lastDate2 / 86400) != Int(dateNum / 86400)
                        {
                            lastDate2 = dateNum
                            lastYear = year
                            let tSize = paint.textSize(text:xText, font:"Default,12")
                            let x = getChartX(chart:chart, index:i)
                            let dx = x + 2
                            if dx > dLeft && dx + tSize.cx < chart.size.cx - chart.rightVScaleWidth - 5
                            {
                                let bBottom = chart.size.cy
                                paint.drawLine(color:chart.scaleColor, width:1, style:[], x1:x, y1:bBottom - chart.hScaleHeight, x2:x, y2:bBottom - chart.hScaleHeight + 12)
                                paint.drawText(text:xText, color:chart.hScaleTextColor, font:"Default,12", x:dx, y:bBottom - chart.hScaleHeight / 2 - tSize.cy / 2)
                                i = i + Int((tSize.cx + chart.hScaleTextDistance) / chart.hScalePixel) + 1
                            }
                        }
                        i =  i + 1
                    }
                }
                else if chart.cycle == "day"{
                    let drawLeft = chart.leftVScaleWidth //左侧起画点
                    var i = chart.firstVisibleIndex //开始索引
                    var lastYear = 0 //缓存年份，用于判断是否换年
                    var drawYearsCache = [Int]() //实际绘制到图形上的年份文字
                    var lastTextRight = 0.0 //上个文字的右侧
                    var timeCache = [Date]() //保存日期的缓存
                    var yearTextLeftCache = [Double]() //绘制年文字的左侧位置缓存
                    var yearTextRightCache = [Double]() //绘制年文字的右侧位置缓存
                    let textPadding = 5.0 //两个文字之间的最小间隔
                    //逐步递增索引，先绘制年
                    while i <= chart.lastVisibleIndex{
                        let timeInterval:TimeInterval = TimeInterval(chart.datas[i].date)
                        let dateObj = Date(timeIntervalSince1970: timeInterval)
                        timeCache.append(dateObj)
                        let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dateObj)
                        let year = Int(components.year!) //从结构中获取年份
                        let x = getChartX(chart:chart, index:i) //获取索引对应的位置
                        //判断是否换年，以及是否在绘图区间内
                        if year != lastYear && x >= drawLeft && x < chart.size.cx - chart.rightVScaleWidth{
                            let month = Int(components.month!)  //获取月的结构
                            var xText = String(year) //拼接要绘制的文字
                            if month < 10{
                                xText = xText + "/0" + String(month) //如果小于10月要补0
                            }
                            else{
                                xText = xText + "/" + String(month) //大于等于10月不用补0
                            }
                            let tSize = paint.textSize(text:xText, font:chart.font) //计算要绘制文字的大小
                            paint.drawLine(color:chart.scaleColor, width:1, style:[], x1:x, y1:chart.size.cy - chart.hScaleHeight, x2:x, y2:chart.size.cy - chart.hScaleHeight + 8) //绘制刻度线
                            //判断是否和上个文字重影
                            if x + 2 > lastTextRight + textPadding{
                                paint.drawText(text:xText, color:chart.hScaleTextColor, font:"Default,12", x:x + 2, y:chart.size.cy - chart.hScaleHeight + 8  - tSize.cy / 2 + 7) //绘制文字
                                yearTextLeftCache.append(x + 2) //将年文字的左侧位置缓存
                                yearTextRightCache.append(x + 2 + tSize.cx) //将年文字的右侧位置缓存
                                drawYearsCache.append(year) //缓存要绘制的年
                                lastTextRight = x + 2 + tSize.cx //缓存上个文字的右侧位置
                            }
                            lastYear = year //记录上次绘制的年份
                        }
                        i = i + 1    //索引累加
                    }
                    //绘制月份
                    if drawYearsCache.count > 0{
                        for m in 0...drawYearsCache.count - 1{
                            let cacheYear = drawYearsCache[m] //从缓存中获取年份
                            var lastMonth = 0 //缓存月份，用于判断是否换月
                            i = chart.firstVisibleIndex //重置开始索引
                            lastTextRight = 0 //重置上个文字的右侧
                            //逐步递增索引
                            while i <= chart.lastVisibleIndex{
                                let dateObj = timeCache[i - chart.firstVisibleIndex] //从缓存中获取time
                                let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dateObj)
                                let year = Int(components.year!) //从结构中获取年份
                                //判断是否同一年
                                if cacheYear == year{
                                    let month = Int(components.month!) //从结构中获取月份
                                    let x = getChartX(chart:chart, index:i)
                                    //判断是否换月，以及是否在绘图区间内
                                    if lastMonth != month && x >= drawLeft && x < chart.size.cx - chart.rightVScaleWidth{
                                        let xText = String(month) //获取绘制的月份文字
                                        let tSize = paint.textSize(text:xText, font:chart.font) //计算要绘制文字的大小
                                        //判断是否和上个文字重影
                                        if x + 2 > lastTextRight + textPadding{
                                            if (x + 2 > yearTextRightCache[m] + textPadding)
                                                && ((m == drawYearsCache.count - 1)
                                                    || ((m < drawYearsCache.count - 1)
                                                        && (x + 2 + tSize.cx < yearTextLeftCache[m + 1] - textPadding))){
                                                paint.drawLine(color:chart.scaleColor, width:1, style:[], x1:x, y1:chart.size.cy - chart.hScaleHeight, x2:x, y2:chart.size.cy - chart.hScaleHeight + 6) //绘制刻度
                                                paint.drawText(text:xText, color:chart.hScaleTextColor, font:"Default,12", x:x + 2, y:chart.size.cy - chart.hScaleHeight + 8  - tSize.cy / 2 + 7) //绘制文字
                                                lastTextRight = x + 2 + tSize.cx //缓存上个文字的右侧位置
                                            }
                                        }
                                        lastMonth = month //记录上次绘制的月份
                                    }
                                }
                                else if cacheYear < year{
                                    break //超过区间，退出循环
                                }
                                i = i + 1    //索引累加
                            }
                        }
                    }
                }
            }
        }
    }

    /*
     * 初始化布局
     */
    override func onLoad(){
        let isInit = super.gInit
        super.onLoad()
        if !isInit{
            gPaint.defaultUIStyle = "dark"
            let width = Double(self.frame.size.width), height = Double(self.frame.size.height)
            renderFaceCat(name:"mainframe", paint: gPaint, size: FCSize(cx:width, cy:height))
            gPaint.addPaintEvent(callBack: onPaint)
            gPaint.addClickGridCellEvent(callBack: onClickGridCell)
            gPaint.addClickEvent(callBack: onClick)
            gPaint.addPaintChartHScaleEvent(callBack: drawChartHScale)
            
            gridStocks = findViewByName(name:"gridStocks", views:gPaint.views) as! FCGrid
            for i in 3...gridStocks.columns.count - 1{
                gridStocks.columns[i].cellAlign = "right"
            }
            gridStocks.selectedRowColor = "rgb(75,75,75)"
            gridStocks.alternateRowColor = "rgb(25,25,25)"
            queryPrice(codes:"all")
            
            findViewsByType(findType:"mychart", views:gPaint.views, refViews:&findMyCharts)
            for i in 0...findMyCharts.count - 1{
                let myChart = findMyCharts[i]
                let splitDiv = FCSplitLayoutDiv()
                splitDiv.layoutStyle = "toptobottom"
                splitDiv.size = FCSize(cx:400, cy:400)
                splitDiv.backColor = "none"
                splitDiv.borderColor = "none"
                splitDiv.dock = "fill"
                addViewToParent(view:splitDiv, parent:myChart)

                let topDiv = FCLayoutDiv()
                topDiv.backColor = "none"
                topDiv.borderColor = "none"
                topDiv.layoutStyle = "lefttoright"
                topDiv.showHScrollBar = false
                addViewToParent(view:topDiv, parent:splitDiv)

                let bottomDiv = FCDiv()
                bottomDiv.backColor = "none"
                bottomDiv.borderColor = "none"
                addViewToParent(view:bottomDiv, parent:splitDiv)

                splitDiv.setFirstView(view: topDiv)
                splitDiv.setSecondView(view: bottomDiv)

                let splitter = FCView()
                splitter.setParent(parent: splitDiv)
                if gPaint.defaultUIStyle == "dark" {
                    splitter.backColor = "rgb(75,75,75)"
                } else if gPaint.defaultUIStyle == "light" {
                    splitter.backColor = "rgb(150,150,150)"
                }
                splitter.borderColor = "none"
                splitter.setPaint(paint: gPaint)
                splitDiv.views.append(splitter)
                splitDiv.setSplitter(view: splitter)
                splitter.size = FCSize(cx:400, cy:1)
                splitter.location = FCPoint(x:0, y:30)
                if i == 0{
                    splitter.location = FCPoint(x:0, y:0)
                }

                let chart = FCChart()
                chart.leftVScaleWidth = 70
                chart.rightVScaleWidth = 70
                if i > 0{
                    chart.leftVScaleWidth = 0
                }
                chart.vScaleDistance = 35
                chart.hScalePixel = 11
                chart.hScaleHeight = 30
                chart.candlePaddingTop = 30
                chart.candlePaddingBottom = 20
                chart.volPaddingTop = 20
                chart.volPaddingBottom = 0
                chart.vScaleDistance = 35
                chart.dock = "fill"
                chart.font = "Default,12"
                if let newStr = myChart.exAttributes["candledivpercent"]{
                    chart.candleDivPercent = StringToFloat(str:newStr)
                }
                if let newStr2 = myChart.exAttributes["voldivpercent"]{
                    chart.volDivPercent = StringToFloat(str:newStr2)
                }
                chart.indDivPercent = 0
                if (self.isMobile) {
                    chart.rightVScaleWidth = 0
                    chart.leftVScaleWidth = 60
                }
                chart.text = strCode + " " + strName
                if let strCycle = myChart.exAttributes["cycle"]{
                    let intCycle = Int(strCycle)!
                    if intCycle == 0{
                        chart.text += " 分时"
                    }else if intCycle < 1440{
                        chart.text += " " + String(intCycle) + "分钟"
                    }else if intCycle == 1440{
                        chart.text += " 日线"
                    }else if intCycle == 10080{
                        chart.text += " 周线"
                    }else if intCycle == 43200{
                        chart.text += " 月线"
                    }
                }
                chart.allowDragChartDiv = true
                charts.append(chart)
                addViewToParent(view:chart, parent:bottomDiv)
                toBlackChart(chart:chart, index:Int32(i))
                queryHistoryData(mychart:myChart, chart:chart, code:strCode)

                var cycles = [String]()
                cycles.append("1")
                cycles.append("5")
                cycles.append("10")
                cycles.append("15")
                cycles.append("20")
                cycles.append("30")
                cycles.append("60")
                cycles.append("90")
                cycles.append("120")
                cycles.append("日")
                cycles.append("周")
                cycles.append("月")
                cycles.append("季")
                cycles.append("半")
                cycles.append("年")
                
                var cyclesInts = [Int]()
                cyclesInts.append(1)
                cyclesInts.append(5)
                cyclesInts.append(10)
                cyclesInts.append(15)
                cyclesInts.append(20)
                cyclesInts.append(30)
                cyclesInts.append(60)
                cyclesInts.append(90)
                cyclesInts.append(120)
                cyclesInts.append(1440)
                cyclesInts.append(10080)
                cyclesInts.append(43200)
                cyclesInts.append(129600)
                cyclesInts.append(259200)
                cyclesInts.append(518400)
                for c in 0...cycles.count - 1{
                    let cycleButton = FCButton()
                    cycleButton.text = cycles[c]
                    cycleButton.size = FCSize(cx:27, cy:30)
                    cycleButton.textColor = "rgb(200,200,200)"
                    cycleButton.borderColor = "rgb(50,50,50)"
                    cycleButton.backColor = "none"
                    cycleButton.viewName = "cycle," + String(i) + "," + String(cyclesInts[c])
                    addViewToParent(view:cycleButton, parent:topDiv)
                }
            }
            queryNewData(code:strCode)
            updateViewDefault(views:gPaint.views)
            invalidate(paint:gPaint)
        }
    }
}
